package com.anan.builder;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class BuildConfig {

    public static void create(String projectName) {

        createInterceptor(projectName);
        createInterceptorConfig(projectName);
        createRedisConfig(projectName);
        createAppConfig(projectName);
    }

    private static void createAppConfig(String projectName) {
        String path = System.getProperty("user.dir") + "/" + projectName + "/src/main/java/com/anan/config";
        File file = new File(path);
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            if (!mkdirs) {
                throw new RuntimeException("创建 " + path + " 目录失败");
            }
        }
        File beanFile = new File(path, "AppConfig.java");
        OutputStream out = null;
        OutputStreamWriter outw = null;
        BufferedWriter bw = null;
        try {
            out = new FileOutputStream(beanFile);
            outw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            bw = new BufferedWriter(outw);
            bw.write("package com.anan.config;\n" +
                    "\n" +
                    "import org.slf4j.Logger;\n" +
                    "import org.slf4j.LoggerFactory;\n" +
                    "import org.springframework.beans.factory.annotation.Value;\n" +
                    "import org.springframework.stereotype.Component;\n" +
                    "\n" +
                    "\n" +
                    "@Component(\"appConfig\")\n" +
                    "public class AppConfig {\n" +
                    "\n" +
                    "    private static final Logger logger = LoggerFactory.getLogger(AppConfig.class);\n" +
                    "\n" +
                    "\n" +
                    "    /**\n" +
                    "     * 文件目录\n" +
                    "     */\n" +
                    "    @Value(\"${project.folder}\")\n" +
                    "    private String projectFolder;\n" +
                    "//    private String projectFolder = System.getProperty(\"user.dir\") ;\n" +
                    "\n" +
                    "    /**\n" +
                    "     * 发送人\n" +
                    "     */\n" +
                    "    @Value(\"${spring.mail.username}\")\n" +
                    "    private String sendUserName;\n" +
                    "\n" +
                    "\n" +
                    "    @Value(\"${admin.emails}\")\n" +
                    "    private String adminEmails;\n" +
                    "\n" +
                    "    @Value(\"${dev}\")\n" +
                    "    private Boolean dev;\n" +
                    "\n" +
                    "\n" +
                    "    @Value(\"${qq.app.id}\")\n" +
                    "    private String qqAppId;\n" +
                    "\n" +
                    "    @Value(\"${qq.app.key}\")\n" +
                    "    private String qqAppKey;\n" +
                    "\n" +
                    "\n" +
                    "    @Value(\"${qq.url.authorization}\")\n" +
                    "    private String qqUrlAuthorization;\n" +
                    "\n" +
                    "\n" +
                    "    @Value(\"${qq.url.access.token}\")\n" +
                    "    private String qqUrlAccessToken;\n" +
                    "\n" +
                    "\n" +
                    "    @Value(\"${qq.url.openid}\")\n" +
                    "    private String qqUrlOpenId;\n" +
                    "\n" +
                    "    @Value(\"${qq.url.user.info}\")\n" +
                    "    private String qqUrlUserInfo;\n" +
                    "\n" +
                    "    @Value(\"${qq.url.redirect}\")\n" +
                    "    private String qqUrlRedirect;\n" +
                    "\n" +
                    "    @Value(\"${url}\")\n" +
                    "    private String url;\n" +
                    "\n" +
                    "    @Value(\"${path.resources}\")\n" +
                    "    private String staticPathResources;\n" +
                    "\n" +
                    "    @Value(\"${prefix.path}\")\n" +
                    "    private String visitStaticResourcesPrefix;" +
                    "\n" +
                    "    public String getProjectFolder() {\n" +
                    "        if (!projectFolder.isEmpty() && !projectFolder.endsWith(\"/\")) {\n" +
                    "            projectFolder = projectFolder + \"/\";\n" +
                    "        }\n" +
                    "        return projectFolder;\n" +
                    "    }\n" +
                    "\n" +
                    "\n" +
                    "    public void setProjectFolder(String projectFolder) {\n" +
                    "        this.projectFolder = projectFolder;\n" +
                    "    }\n" +
                    "\n" +
                    "    public String getSendUserName() {\n" +
                    "        return sendUserName;\n" +
                    "    }\n" +
                    "\n" +
                    "    public void setSendUserName(String sendUserName) {\n" +
                    "        this.sendUserName = sendUserName;\n" +
                    "    }\n" +
                    "\n" +
                    "    public String getAdminEmails() {\n" +
                    "        return adminEmails;\n" +
                    "    }\n" +
                    "\n" +
                    "    public void setAdminEmails(String adminEmails) {\n" +
                    "        this.adminEmails = adminEmails;\n" +
                    "    }\n" +
                    "\n" +
                    "    public Boolean getDev() {\n" +
                    "        return dev;\n" +
                    "    }\n" +
                    "\n" +
                    "    public void setDev(Boolean dev) {\n" +
                    "        this.dev = dev;\n" +
                    "    }\n" +
                    "\n" +
                    "    public String getQqAppId() {\n" +
                    "        return qqAppId;\n" +
                    "    }\n" +
                    "\n" +
                    "    public void setQqAppId(String qqAppId) {\n" +
                    "        this.qqAppId = qqAppId;\n" +
                    "    }\n" +
                    "\n" +
                    "    public String getQqAppKey() {\n" +
                    "        return qqAppKey;\n" +
                    "    }\n" +
                    "\n" +
                    "    public void setQqAppKey(String qqAppKey) {\n" +
                    "        this.qqAppKey = qqAppKey;\n" +
                    "    }\n" +
                    "\n" +
                    "    public String getQqUrlAuthorization() {\n" +
                    "        return qqUrlAuthorization;\n" +
                    "    }\n" +
                    "\n" +
                    "    public void setQqUrlAuthorization(String qqUrlAuthorization) {\n" +
                    "        this.qqUrlAuthorization = qqUrlAuthorization;\n" +
                    "    }\n" +
                    "\n" +
                    "    public String getQqUrlAccessToken() {\n" +
                    "        return qqUrlAccessToken;\n" +
                    "    }\n" +
                    "\n" +
                    "    public void setQqUrlAccessToken(String qqUrlAccessToken) {\n" +
                    "        this.qqUrlAccessToken = qqUrlAccessToken;\n" +
                    "    }\n" +
                    "\n" +
                    "    public String getQqUrlOpenId() {\n" +
                    "        return qqUrlOpenId;\n" +
                    "    }\n" +
                    "\n" +
                    "    public void setQqUrlOpenId(String qqUrlOpenId) {\n" +
                    "        this.qqUrlOpenId = qqUrlOpenId;\n" +
                    "    }\n" +
                    "\n" +
                    "    public String getQqUrlUserInfo() {\n" +
                    "        return qqUrlUserInfo;\n" +
                    "    }\n" +
                    "\n" +
                    "    public void setQqUrlUserInfo(String qqUrlUserInfo) {\n" +
                    "        this.qqUrlUserInfo = qqUrlUserInfo;\n" +
                    "    }\n" +
                    "\n" +
                    "    public String getQqUrlRedirect() {\n" +
                    "        return qqUrlRedirect;\n" +
                    "    }\n" +
                    "\n" +
                    "    public void setQqUrlRedirect(String qqUrlRedirect) {\n" +
                    "        this.qqUrlRedirect = qqUrlRedirect;\n" +
                    "    }\n" +
                    "\n" +
                    "    public void setUrl(String url) {\n" +
                    "        this.url = url;\n" +
                    "    }\n" +
                    "\n" +
                    "    public String getUrl() {\n" +
                    "        return url;\n" +
                    "    }\n" +

                    "\n" +
                    "   public String getStaticPathResources() {\n" +
                    "        return staticPathResources;\n" +
                    "    }\n" +
                    "\n" +
                    "    public void setStaticPathResources(String staticPathResources) {\n" +
                    "        this.staticPathResources = staticPathResources;\n" +
                    "    }\n" +
                    "\n" +
                    "    public String getVisitStaticResourcesPrefix() {\n" +
                    "        return visitStaticResourcesPrefix;\n" +
                    "    }\n" +
                    "\n" +
                    "    public void setVisitStaticResourcesPrefix(String visitStaticResourcesPrefix) {\n" +
                    "        this.visitStaticResourcesPrefix = visitStaticResourcesPrefix;\n" +
                    "    }" +
                    "}\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != bw) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outw != null) {
                try {
                    outw.close();
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

    private static void createRedisConfig(String projectName) {
        String path = System.getProperty("user.dir") + "/" + projectName + "/src/main/java/com/anan/config";
        File file = new File(path);
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            if (!mkdirs) {
                throw new RuntimeException("创建 " + path + " 目录失败");
            }
        }
        File beanFile = new File(path, "RedisConfig.java");
        OutputStream out = null;
        OutputStreamWriter outw = null;
        BufferedWriter bw = null;
        try {
            out = new FileOutputStream(beanFile);
            outw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            bw = new BufferedWriter(outw);
            bw.write("package com.anan.config;\n" +
                    "\n" +
                    "import org.springframework.context.annotation.Bean;\n" +
                    "import org.springframework.context.annotation.Configuration;\n" +
                    "import org.springframework.data.redis.connection.RedisConnectionFactory;\n" +
                    "import org.springframework.data.redis.core.RedisTemplate;\n" +
                    "import org.springframework.data.redis.serializer.RedisSerializer;\n" +
                    "\n" +
                    "/**\n" +
                    " * 用于配置 RedisTemplate 的序列化方式的。它的作用是将 Redis 中的 key 和 value 进行序列化和反序列化，以便存储和读取 Java 对象。\n" +
                    " * @param <V>\n" +
                    " */\n" +
                    "@Configuration(\"redisConfig\")  // 表示将该类标识为配置类，并指定了一个名称为 \"redisConfig\"；\n" +
                    "public class RedisConfig<V> {\n" +
                    "\n" +
                    "    @Bean  // 表示将该方法返回的对象交给 Spring 容器管理;  RedisTemplate<String, V> 表示 RedisTemplate 的泛型类型，其中 String 表示 key 的类型，V 表示 value 的类型；\n" +
                    "    public RedisTemplate<String, V> redisTemplate(RedisConnectionFactory factory) {  // RedisConnectionFactory factory 表示 Redis 连接工厂，由 Spring 自动注入\n" +
                    "        RedisTemplate<String, V> template = new RedisTemplate<>();  // RedisTemplate 对象\n" +
                    "        template.setConnectionFactory(factory);  // 这段代码是用于设置 RedisTemplate 的连接工厂的。它的作用是将 RedisTemplate 与 RedisConnectionFactory 关联起来，以便进行连接和操作 Redis 数据库。\n" +
                    "        // 设置key的序列化方式\n" +
                    "        template.setKeySerializer(RedisSerializer.string());  //  表示设置 key 的序列化方式为 StringRedisSerializer，即将 key 序列化为字符串\n" +
                    "        // 设置value的序列化方式\n" +
                    "        template.setValueSerializer(RedisSerializer.json());  // 表示设置 value 的序列化方式为 Jackson2JsonRedisSerializer，即将 value 序列化为 JSON 字符串；\n" +
                    "        // 设置hash的key的序列化方式\n" +
                    "        template.setHashKeySerializer(RedisSerializer.string());\n" +
                    "        // 设置hash的value的序列化方式\n" +
                    "        template.setHashValueSerializer(RedisSerializer.json());\n" +
                    "        template.afterPropertiesSet();  // 表示初始化 RedisTemplate 对象。\n" +
                    "        return template;\n" +
                    "    }\n" +
                    "}\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != bw) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outw != null) {
                try {
                    outw.close();
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

    private static void createInterceptorConfig(String projectName) {
        String path = System.getProperty("user.dir") + "/" + projectName + "/src/main/java/com/anan/config";
        File file = new File(path);
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            if (!mkdirs) {
                throw new RuntimeException("创建 " + path + " 目录失败");
            }
        }
        File beanFile = new File(path, "InterceptorConfig.java");
        OutputStream out = null;
        OutputStreamWriter outw = null;
        BufferedWriter bw = null;
        try {
            out = new FileOutputStream(beanFile);
            outw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            bw = new BufferedWriter(outw);
            bw.write("package com.anan.config;\n" +
                    "\n" +
                    "\n" +
                    "import org.springframework.context.annotation.Configuration;\n" +
                    "import org.springframework.web.servlet.config.annotation.CorsRegistry;\n" +
                    "import org.springframework.web.servlet.config.annotation.InterceptorRegistry;\n" +
                    "import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;\n" +
                    "import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;\n" +
                    "\n" +
                    "\n" +
                    "@Configuration\n" +
                    "public class InterceptorConfig extends WebMvcConfigurationSupport {\n" +
                    "\n" +
                    "    @Resource\n" +
                    "    private AppConfig appConfig;\n" +
                    "\n" +
                    "    /**\n" +
                    "     * 用于配置 Spring MVC 的拦截器的。它的作用是拦截所有请求，并对请求进行一些处理，如：日志记录、权限校验等。\n" +
                    "     * @param registry\n" +
                    "     */\n" +
                    "    @Override\n" +
                    "    public void addInterceptors(InterceptorRegistry registry) {\n" +
                    "        registry.addInterceptor(new Interceptor())  // 添加一个拦截器\n" +
                    "                .addPathPatterns(\"/**\")  // 拦截所有请求\n" +
                    "                .excludePathPatterns(\"/static/**\");  // 排除请求\n" +
                    "    }\n" +
                    "\n" +
                    "\n" +
                    "    /**\n" +
                    "     * springboot 2.0配置WebMvcConfigurationSupport之后，会导致默认配置被覆盖，要访问静态资源需要重写addResourceHandlers方法\n" +
                    "     */\n" +
                    "    @Override\n" +
                    "    public void addResourceHandlers(ResourceHandlerRegistry registry) {\n" +
                    "        registry.addResourceHandler(appConfig.getVisitStaticResourcesPrefix() + \"/**\")  // 对所有的 URL 进行静态资源映射的配置；\n" +
                    "                .addResourceLocations(\"file:\" + appConfig.getStaticPathResources() + File.separator);  // 表示将静态资源文件路径设置为 classpath:/static/，即在 classpath 路径下的 static 文件夹中。这里可以配置多个静态资源文件夹路径，用逗号隔开即可。\n" +
                    "    }\n" +
                    "\n" +
                    "\n" +
                    "    // 设置跨域请求\n" +
                    "    @Override\n" +
                    "    protected void addCorsMappings(CorsRegistry registry) {\n" +
                    "        registry.addMapping(\"/**\")  //所有的 URL 进行跨域资源共享的配置；\n" +
                    "                .allowedOrigins(\"*\")  //允许来自任何来源（包括不同域名、端口或协议）的请求访问资源；\n" +
                    "                .allowedHeaders(\"*\")\n" +
                    "                .allowedMethods(\"*\")    //允许的请求方法，这里设置为 \"*\" 表示允许所有 HTTP 方法；\n" +
                    "                .maxAge(24 * 60 * 60);//响应的最大时长，这里设置为 24 小时。\n" +
                    "    }\n" +
                    "\n" +
                    "}\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != bw) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outw != null) {
                try {
                    outw.close();
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    private static void createInterceptor(String projectName) {
        String path = System.getProperty("user.dir") + "/" + projectName + "/src/main/java/com/anan/config";
        File file = new File(path);
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            if (!mkdirs) {
                throw new RuntimeException("创建 " + path + " 目录失败");
            }
        }
        File beanFile = new File(path, "Interceptor.java");
        OutputStream out = null;
        OutputStreamWriter outw = null;
        BufferedWriter bw = null;
        try {
            out = new FileOutputStream(beanFile);
            outw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            bw = new BufferedWriter(outw);
            bw.write("package com.anan.config;\n" +
                    "\n" +
                    "import org.springframework.web.servlet.HandlerInterceptor;\n" +
                    "import org.springframework.web.servlet.ModelAndView;\n" +
                    "\n" +
                    "import javax.servlet.http.HttpServletRequest;\n" +
                    "import javax.servlet.http.HttpServletResponse;\n" +
                    "import javax.servlet.http.HttpSession;\n" +
                    "\n" +
                    "// 拦截器\n" +
                    "public class Interceptor implements HandlerInterceptor {\n" +
                    "\n" +
                    "    @Override\n" +
                    "    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {\n" +
                    "        HttpSession session = request.getSession();  // 会话\n" +
                    "        // 获取会话信息 校验登录\n" +
                    "\n" +
                    "\n" +
                    "//        StringBuffer requestURL = request.getRequestURL();  // 请求完整url\n" +
                    "//        String contextPath = request.getContextPath();  // 上下文路径 /api\n" +
                    "//        String servletPath = request.getServletPath();  // 请求路径 例如 /login\n" +
                    "//        System.out.println(requestURL);\n" +
                    "//        System.out.println(contextPath);\n" +
                    "//        System.out.println(servletPath);\n" +
                    "\n" +
                    "\n" +
                    "        return true;\n" +
                    "//        if (requestURL != null) {\n" +
                    "//            return true;  // 放行\n" +
                    "//        } else {\n" +
                    "//            // 重定向\n" +
                    "////            request.getRequestDispatcher(\"/\").forward(request,response);\n" +
                    "//            return false;  // 拦截\n" +
                    "//        }\n" +
                    "    }\n" +
                    "\n" +
                    "    @Override\n" +
                    "    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {\n" +
                    "        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);\n" +
                    "    }\n" +
                    "\n" +
                    "    @Override\n" +
                    "    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {\n" +
                    "        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);\n" +
                    "    }\n" +
                    "}\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != bw) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outw != null) {
                try {
                    outw.close();
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
